#!/opt/bin/python

import os, sys, urllib

print '<?xml version="1.0" encoding="UTF-8"?><atv><body>'

uri = os.environ['QUERY_STRING'] if ('QUERY_STRING' in os.environ) else 'media/DATA/Videos'
if os.path.splitext(uri)[1] in ('.mp4', '.mov'):
	print '<videoPlayer id="player"><httpFileVideoAsset id="asset">'
	print '<mediaURL>http://router/%s</mediaURL>' % uri
	print '</httpFileVideoAsset></videoPlayer>'

else:
	i = 0;
	dir = '/opt/etc/www/' + urllib.unquote(uri)
	files = os.listdir(dir) if os.path.isdir(dir) else []
	files.sort(None, None, True)
	print '<scroller id="scroller"><items><grid columnCount="5" id="grid"><items>'
	for f in files:
		dir2 = dir + '/' + f
		if (f[0] != '.') and os.path.isdir(dir2):
			files2 = os.listdir(dir2)
			for f2 in files2:
				if os.path.isdir(dir2 + '/' + f2) or os.path.splitext(f2)[1] in ('.mp4', '.mov'):
					i += 1
					url = 'http://router/appletv/video.py?' + uri + '/' + urllib.quote(f)
					print '<sixteenByNinePoster alwaysShowTitles="true" id="dir%d" onPlay="atv.loadURL(\'%s\')" onSelect="atv.loadURL(\'%s\')">' % (i, url, url)
					print '<title>%s</title>' % f
					print '<image>http://router/appletv/image/folder.png</image>'
					print '<defaultImage>resource://Poster.png</defaultImage>'
					print '</sixteenByNinePoster>'
					break
	for f in files:
		if os.path.splitext(f)[1] in ('.mov', '.mp4'):
			i += 1
			url = 'http://router/appletv/video.py?' + uri + '/' + urllib.quote(f)
			print '<sixteenByNinePoster alwaysShowTitles="true" id="mov%d" onPlay="atv.loadURL(\'%s\')" onSelect="atv.loadURL(\'%s\')">' % (i, url, url)
			print '<title>%s</title>' % f.split('.')[0]
			print '<image>http://router/appletv/image/file.png</image>'
			print '<defaultImage>resource://Play.png</defaultImage>'
			print '</sixteenByNinePoster>'
	print '</items></grid></items></scroller>'

print '</body></atv>'
